import { param2Obj } from "@/utils";
import Mock from "mockjs";

let list = [];
const count = 10;

// 模拟数据
for (let i = 0; i < count; i++) {
  list.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      birth: Mock.Random.date(),
    })
  );
}

const get = {
  url: "/api/list",
  type: "get",
  response: (options) => {
    const { name, pageNum = 1, pageSize = 10 } = param2Obj(options.url);
    // 过滤条件
    const mockList = list.filter((user) => {
      if (name && user.name.indexOf(name) === -1) return false;
      return true;
    });
    // 处理分页
    const pageList = mockList.filter(
      (item, index) =>
        index < pageSize * pageNum && index >= pageSize * (pageNum - 1)
    );
    return {
      code: 200,
      data: pageList,
      totalNum: mockList.length,
    };
  },
};

const add = {
  url: "/api/user",
  type: "post",
  response: (options) => {
    const data = JSON.parse(options.body);
    list.push({ id: Mock.Random.guid(), ...data });
    return {
      code: 200,
      msg: "添加人员成功!",
    };
  },
};

const update = {
  url: "/api/user",
  type: "put",
  response: (options) => {
    const data = JSON.parse(options.body);
    const id = options.url.split("/")[options.url.split("/").length - 1];
    // 使用some对满足条件值进行覆盖
    list.some((t) => {
      if (t.id === id) {
        console.log(t);
        t.name = data.name;
        t.birth = data.birth;
        return true;
      }
    });
    return {
      code: 200,
      msg: "修改人员成功!",
    };
  },
};

const del = {
  url: "/api/user",
  type: "delete",
  response: (options) => {
    const id = options.url.split("/")[options.url.split("/").length - 1];
    list = list.filter((t) => t.id != id);
    return {
      code: 200,
      msg: "删除人员成功!",
    };
  },
};

export default [get, add, update, del];
